//
//  MachineHandler.m
//  recordTest
//
//  Created by Jason on 2017/5/31.
//  Copyright © 2017年 LiuYu. All rights reserved.
//

#import "MachineHandler.h"

@implementation MachineHandler

@end

/*********************************************************************************************************/
@implementation SpeechHandler
- (instancetype)init
{
    self = [super init];
    if (self) {
        _speechType = LY_CHINA;//默认中文
        
        [SFSpeechRecognizer  requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                switch (status) {
                    case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                        
                        //语音识别未授权
                        break;
                    case SFSpeechRecognizerAuthorizationStatusDenied:
                        
                        //用户未授权使用语音识别
                        break;
                    case SFSpeechRecognizerAuthorizationStatusRestricted:
                        
                        //语音识别在这台设备上受到限制
                        
                        break;
                    case SFSpeechRecognizerAuthorizationStatusAuthorized:
                        NSLog(@"AUTH");
                        //授权成功
                        break;
                    default:
                        break;
                }
                
            });
        }];
    }
    return self;
}

- (void)setSpeechType:(SPEECH_COUNTY)type{
    _speechType = type;
    if (_speechRecognizer) {
        _speechRecognizer = nil;
    }
}

- (void)start{
    if (!self.audioEngine.isRunning) {

        [self startRecording];
        //[self.recordButton setTitle:@"停止录音" forState:UIControlStateNormal];
    }
}

- (void)stop:(LY_SPEECH)suc{
    _stop_block = suc;
    [self.audioEngine stop];
    if (_recognitionRequest) {
        [_recognitionRequest endAudio];
    }
    
}

- (void)startRecording{
    
    if (_recognitionTask) {
        [_recognitionTask cancel];
        _recognitionTask = nil;
    }
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error;
    [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
    NSParameterAssert(!error);
    [audioSession setMode:AVAudioSessionModeMeasurement error:&error];
    NSParameterAssert(!error);
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    NSParameterAssert(!error);
    
    _recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
    NSAssert(inputNode, @"录入设备没有准备好");
    NSAssert(_recognitionRequest, @"请求初始化失败");
    _recognitionRequest.shouldReportPartialResults = YES;
    __weak typeof(self) weakSelf = self;
    _recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:_recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        BOOL isFinal = NO;
        if (result) {
            NSString *str = result.bestTranscription.formattedString;
            weakSelf.block(str);//
            isFinal = result.isFinal;
        }
        if (error || isFinal) {
            [self.audioEngine stop];
            [inputNode removeTapOnBus:0];
            strongSelf.recognitionTask = nil;
            strongSelf.recognitionRequest = nil;
            [weakSelf startRecording];
        }
        NSLog(@"error= %@",error);
    }];
    
    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
    [inputNode installTapOnBus:0 bufferSize:120 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf.recognitionRequest) {
            [strongSelf.recognitionRequest appendAudioPCMBuffer:buffer];
        }
    }];
    
    [self.audioEngine prepare];
    [self.audioEngine startAndReturnError:&error];
    NSParameterAssert(!error);

}

// - lazyLoad
- (AVAudioEngine *)audioEngine{
    if (!_audioEngine) {
        _audioEngine = [[AVAudioEngine alloc] init];
    }
    return _audioEngine;
}

- (SFSpeechRecognizer *)speechRecognizer{
    if (!_speechRecognizer) {
        //腰围语音识别对象设置语言，这里设置的是中文
        NSLocale *local = nil;
        if (_speechType == LY_CHINA) {
            local =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        }else{
            local =[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        }
        
        _speechRecognizer =[[SFSpeechRecognizer alloc] initWithLocale:local];
        _speechRecognizer.delegate = self;
    }
    return _speechRecognizer;
}
#pragma mark - SFSpeechRecognizerDelegate
- (void)speechRecognizer:(SFSpeechRecognizer *)speechRecognizer availabilityDidChange:(BOOL)available{
    if (available) {
        if (_stop_block) {
            _stop_block(available);
        }
        NSLog(@"ss");
       // [self.recordButton setTitle:@"开始录音" forState:UIControlStateNormal];
    }
    else{
NSLog(@"sss");
        //[self.recordButton setTitle:@"语音识别不可用" forState:UIControlStateDisabled];
    }
}
@end
/*********************************************************************************************************/

/*********************************************************************************************************/
@implementation TorchHandler

- (void)turnTorchOn:(bool)isOpen{

    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            if (isOpen) {
                [device setTorchMode:AVCaptureTorchModeOn];
                _isOpen = YES;
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                _isOpen = NO;
            }
            [device unlockForConfiguration];
        }
    }
}

@end


/*********************************************************************************************************/
